#include "gmain.h"
//
/*  Save file as gmain.cpp  */
/*  incomming class name Gmain */
//










#include <QCloseEvent>
//
QPointer<Gmain> Gmain::_self = 0L;
//
Gmain* Gmain::self( QWidget* parent )
{
	if ( !_self )
	_self = new Gmain( parent );
	return _self;
}
//
Gmain::Gmain( QWidget* parent )
	: QMainWindow( parent )
{
        nummer = 0;
        setupUi( this );
        setAcceptDrops(true);
         #if defined Q_WS_MAC
         setAttribute( Qt::WA_MacMetalStyle );
         #endif
    
    
    
        ////////setDragEnabled(true);
        dbwwwww0 = new DBword();
        tabWidget->setContextMenuPolicy( Qt::CustomContextMenu );
         connect( tabWidget, SIGNAL( customContextMenuRequested( const QPoint & ) ), SLOT( TabMenu() ) );

        taindex = tabWidget->currentIndex(); 
        filer.clear();
        tabWidget->removeTab(0);
        AddTabFile("Untitled file",MIMEISO);
        connect(actionNew_File, SIGNAL(activated()),this, SLOT(NewFile()));
        connect(actionSave_current, SIGNAL(activated()),this, SLOT(SaveCurrentFile()));
        connect(actionSave_as, SIGNAL(activated()),this, SLOT(SavecopyFile()));
        connect(actionKeyWords, SIGNAL(activated()),this, SLOT(KeyWords()));
        connect(actionExport_Words, SIGNAL(activated()),this, SLOT(KeyWordsExport()));
        connect(actionExport_SQL_Words, SIGNAL(activated()),this, SLOT(KeyWordsExportSQL()));
         connect(actionOpen_File, SIGNAL(activated()),this, SLOT(OpenFileLocal()));
        QAction *actionSetting_Style = new QAction(this);
        actionSetting_Style->setText(tr("Setting Style"));
        connect(actionSetting_Style, SIGNAL(activated()),this, SLOT(ModStyle()));
        menuFile->addAction(actionSetting_Style);
    /////void Gmain::ModStyle()
    

    
    #if defined(Q_WS_MAC) 
    QMenu *menu = new QMenu();
    QAction *openweb = new QAction(this);
    openweb->setText(tr("New File"));
    openweb->setStatusTip(tr("New File")); 
    connect(openweb, SIGNAL(activated()), this,  SLOT(NewFile()));
    QAction *openweb1 = new QAction(this);
    openweb1->setText(tr("Open local file"));
    openweb1->setStatusTip(tr("Open local file")); 
    connect(openweb1, SIGNAL(activated()), this,  SLOT(OpenFileLocal()));
    qt_mac_set_dock_menu(menu);
    #endif
    
    
    
    
    
    
        searchdlg = new MeSearchDlg(this); 
        searchdlg->hide();

        connect(searchdlg->dd1, SIGNAL(clicked()),this, SLOT(FinderIn()));
         connect(searchdlg->dd2, SIGNAL(clicked()),this, SLOT(FinderIn()));

}

void Gmain::dragEnterEvent(QDragEnterEvent *e)
{
  e->acceptProposedAction();
}

void Gmain::cleanall()
{
  dbwwwww0->dbquit();
}


void Gmain::dropEvent(QDropEvent *e)
{
    
    if(e && e->mimeData()) {
        const QMimeData *data = e->mimeData();
        QStringList urlmixed;
        urlmixed.clear();
        
        QList<QUrl> urlelist;
           if (data->hasUrls()) {
                  urlelist = data->urls(); 
               for ( int i = 0; i < urlelist.size(); ++i ) { 
                   QUrl gettyurl(urlelist.at(i));
                         if (gettyurl.scheme() == "file") {
                             QString localfileupsgo = gettyurl.toLocalFile();
                             
                             OpenFile(localfileupsgo); 
                             
                             urlmixed.append(localfileupsgo);  
                         }
                   
               }
               
           }
        
        
           qDebug() << "### urlmixed " << urlmixed; 
           /////////QMessageBox::warning(0, tr("Message"),tr("Tot %1 file.").arg(urlmixed.size()));
        
    }
        
        
}
void Gmain::KeyWords()
{
    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
    QString fullFileName = WORK_CACHEDIR+"tmp/keylog.txt";
    
     QStringList wes = dbwwwww0->PaintListWord();
    
    bool sx = fwriteutf8(fullFileName,wes.join("\n"));
    if (sx) {
        OpenFile(fullFileName);
    }
    QApplication::restoreOverrideCursor();
}


void Gmain::KeyWordsExportSQL()
{

         bool ok;
     QString fileName = QFileDialog::getSaveFileName(this, "Export KeyWords SQL.",QString(setter.value("LastDir").toString()), "*.sql");
    if (fileName.size() > 1) {
        
            if (!fileName.endsWith(".sql")) {
            fileName = fileName+".sql"; 
            }
            
        
            QString im = fileName;
            QString pathimage = im.left(im.lastIndexOf("/"))+"/";
            setter.setValue("LastDir",pathimage);
        
             QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
    //////////////QString fullFileName = "tmp/keylog.txt";
     QString wes = dbwwwww0->ExportTable_sql();
    bool sx = fwriteutf8(fileName,wes);
    QApplication::restoreOverrideCursor();
        
    }

}

void Gmain::MulitpleOpenFiles( QStringList files )
{
    
                for (int i = 0; i < files.size(); ++i) {
                   OpenFile(files.at(i)); 
                }
}


void Gmain::OpenFileLocal()
{
     bool ok;
     QStringList fileName = QFileDialog::getOpenFileNames(this, "Open Text files",QString(setter.value("LastDir").toString()), "*");
     if (fileName.size() > 0) {
         
         RemoveNullFile();
         
               MulitpleOpenFiles(fileName);
        
        
        
    }
    
}



void Gmain::KeyWordsExport()
{
    
     bool ok;
     QString fileName = QFileDialog::getSaveFileName(this, "Export KeyWords.",QString(setter.value("LastDir").toString()), "*");
    if (fileName.size() > 1) {
    
    QString im = fileName;
    QString pathimage = im.left(im.lastIndexOf("/"))+"/";
     setter.setValue("LastDir",pathimage);
        
        
        
    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
    //////////////QString fullFileName = "tmp/keylog.txt";
    
     QStringList wes = dbwwwww0->PaintListWord();
    
    bool sx = fwriteutf8(fileName,wes.join("\n"));
    QApplication::restoreOverrideCursor();
        
    }
}





void Gmain::SearchDlg()
{
    taindex = tabWidget->currentIndex();
    qDebug() << "#### SearchDlg dlg show  ->" << taindex; 
    searchdlg->setWindowFlags(Qt::Drawer);
    QPoint pos = searchdlg->pos();
    if (pos.x() < 0)
        pos.setX(0);
    if (pos.y() < 0)
        pos.setY(0);
    searchdlg->move(pos);
    searchdlg->show();
    
      
}



void Gmain::FinderIn()
{

    bool searchalldocs = searchdlg->ooalldocs->isChecked();

    qDebug() << "#### searchalldocs  ->" << searchalldocs;


    taindex = tabWidget->currentIndex();
    QString findtext = searchdlg->wquery->toPlainText();
    QString replace = searchdlg->ramplace->toPlainText();

    if (findtext.size() < 1) {
    QMessageBox::warning(searchdlg, tr("Search Error"),tr("Fill a word to search!")); 
    return;
    }

    bool searchups = searchdlg->ssup->isChecked();
    
    if (searchups) {
    filer[taindex]->find(findtext,QTextDocument::FindBackward);
    } else {
    filer[taindex]->find(findtext);
    }

    
    qDebug() << "#### finder  ->" << findtext; 

}









void Gmain::TabMenu()
{
  taindex = tabWidget->currentIndex();
  qDebug() << "### tabmenu " << taindex;
  QMenu *menu = new QMenu(tabWidget);
  menu->addAction(tr( "Save text CTRL+S" ), this , SLOT( SaveCurrentFile() ));
  menu->addAction(tr( "Save a copy to" ), this , SLOT( SavecopyFile() ));
  menu->addAction(tr( "Close" ), this , SLOT( ClosecurrentTabi() ));
  menu->exec( QCursor::pos() ); 
}


void Gmain::RemovePanelAt( int index )
{
       tabWidget->removeTab(index);
       filer.removeAt(index);
       nummer--;

       if (filer.size() < 1) {
       AddTabFile("Untitled file",MIMEISO);
       }
}

void Gmain::SaveCurrentFile()
{
  taindex = tabWidget->currentIndex();

  if (filer.size() > 0) {
         filer[taindex]->TextSave();
  }
}

void Gmain::SavecopyFile()
{
   taindex = tabWidget->currentIndex();
  if (filer.size() > 0) {
         filer[taindex]->TSaveAS();
  }

}



void Gmain::ClosecurrentTabi()
{
   taindex = tabWidget->currentIndex();
   RemovePanelAt(taindex);

}





void Gmain::RemoveNullFile()
{
  for (int i=0;i<filer.size();i++)  {
       bool havefi = filer[i]->HavingFile();
       if (!havefi) {
       RemovePanelAt(i);
       }
  }
}

void Gmain::OpenFile( QUrl onefile )
{
 AddTabFile(onefile.toLocalFile(),MIMEISO);
}

void Gmain::OpenFile( const QString onefile )
{
 AddTabFile(onefile,MIMEISO);
}


void Gmain::NewFile()
{
 AddTabFile("Untitled file",MIMEISO);
}


void Gmain::ModiLabe(const QString file )
{
   TextEdit  *inerente = qobject_cast<TextEdit *>(sender());
    QFileInfo fi(file) ;
   tabWidget->setTabText(tabWidget->currentIndex() ,QString("%2 - %1").arg(fi.fileName()).arg(inerente->GetID())) ;
}




void Gmain::AddTabFile( const QString onefile , OPENMODUS modus )
{
    nummer++;
    QFileInfo fi(onefile) ;

    if (!fi.exists()) {
    
    }
    
     QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
    
    

    QWidget *tabulatore = new QWidget(this);
    QGridLayout *gridLayoutpage = new QGridLayout(tabulatore);
    TextEdit *textEditsection = new TextEdit(tabulatore);
    textEditsection->SetDBinit(dbwwwww0);
    textEditsection->SetID(nummer);
    gridLayoutpage->addWidget(textEditsection, 0, 0, 1, 1);
    QTextEdit *sline = new QTextEdit(tabulatore);
    textEditsection->SetParent(sline);
    QSizePolicy sizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    sizePolicy.setHorizontalStretch(0);
    sizePolicy.setVerticalStretch(0);
    sizePolicy.setHeightForWidth(sline->sizePolicy().hasHeightForWidth());
    sline->setSizePolicy(sizePolicy);
    sline->setMinimumSize(QSize(120, 0));
    sline->setMaximumSize(QSize(120, 16777215));
    sline->setPalette(Palettetexter());
    sline->viewport()->setProperty("cursor", QVariant(QCursor(Qt::ArrowCursor)));
    sline->setFrameShadow(QFrame::Raised);
    sline->setReadOnly(true);
    gridLayoutpage->addWidget(sline, 0, 0, 1, 1);
    gridLayoutpage->addWidget(textEditsection, 0, 1, 1, 1);
    QScrollBar *scrollnummers = sline->verticalScrollBar();
    QScrollBar *scrolltext = textEditsection->verticalScrollBar();
    
    connect( scrolltext, SIGNAL(valueChanged(int)), scrollnummers, SLOT(setValue(int)));
    //////////connect( scrollnummers, SIGNAL(valueChanged(int)), scrolltext, SLOT(setValue(int)));
    connect(textEditsection, SIGNAL(FileSaveTo(QString)),this, SLOT(ModiLabe(QString)));
    connect(textEditsection, SIGNAL(CloseTab()),this, SLOT(ClosecurrentTabi()));
    connect(textEditsection, SIGNAL(SearchText()),this, SLOT(SearchDlg()));
    connect(textEditsection, SIGNAL(OpenFilesmore(QStringList)),this, SLOT(MulitpleOpenFiles(QStringList)));
    connect(textEditsection, SIGNAL(NewFileOpen()),this, SLOT(NewFile()));

    
    
    scrollnummers->setMaximumWidth(1);
    scrollnummers->hide();
  
    if (!fi.exists()) {
    textEditsection->SetFile(onefile,modus);
    tabWidget->addTab(tabulatore,QString("%2 - Untitled file").arg(nummer));
    } else {
    textEditsection->SetFile(onefile,modus);
    tabWidget->addTab(tabulatore, QString("%2 - %1").arg(fi.fileName()).arg(nummer));
        
         QString streams = textEditsection->GetKeyWords();
        keyos.append(streams);
    }
  
    
    filer.append(textEditsection);
    tabWidget->setCurrentIndex ( filer.size() - 1);
    taindex = tabWidget->currentIndex();
    
    QApplication::restoreOverrideCursor();
}















//
void Gmain::Load_Connector()
{
/* to nothing */
/*connect(buttonx, SIGNAL(clicked()), this , SLOT(Make()));*/
  for (int i = 0; i < list.size(); ++i) {   
    std::cout << "### ....." << qPrintable(list.at(i)) << "....." << std::endl; 
     }
     
 /* qDebug() << "#### localedirfile ->" << list.size();   */
     
     
 #if defined Q_WS_MAC
 #endif
 #if defined Q_WS_WIN
 #endif
 #if defined Q_WS_X11
 #endif
}

void Gmain::closeEvent( QCloseEvent* e )
{
	e->accept();
}

/* Q_ASSERT ( bool test )  */ 

/* QString one;  toLower() toUpper()  split(",")  endsWith() startsWith()  QByteArray QString::toAscii() */
/* int nummer; */ 
/* QStringList list;  join();  */ 
/* QUrl url; */ 
/* QByteArray byteArray; */ 
/* bool having; */ 
/* QDomDocument doc;*/ 
/* QDomElement root;*/ 
void Gmain::ModStyle()
{
      QStringList items = QStyleFactory::keys();
      bool ok = false;
     QString soko = QInputDialog::getItem(0,"Select style restart apps.",
                                          "Style:", items, 0, false, &ok);
      if (ok) {
          if (soko.size() > 0 ) {
            setter.setValue("WinStyle",soko);
            QApplication::setStyle(soko);
          }
      }
}












QPalette Gmain::Palettetexter()
{

    QPalette palette;
    QBrush brush(QColor(208, 208, 208, 255));
    brush.setStyle(Qt::SolidPattern);
    palette.setBrush(QPalette::Active, QPalette::Light, brush);
    QBrush brush1(QColor(0, 0, 0, 255));
    brush1.setStyle(Qt::SolidPattern);
    palette.setBrush(QPalette::Active, QPalette::BrightText, brush1);
    QBrush brush2(QColor(223, 223, 223, 255));
    brush2.setStyle(Qt::SolidPattern);
    palette.setBrush(QPalette::Active, QPalette::Base, brush2);
    palette.setBrush(QPalette::Active, QPalette::HighlightedText, brush1);
    palette.setBrush(QPalette::Inactive, QPalette::Light, brush);
    palette.setBrush(QPalette::Inactive, QPalette::BrightText, brush1);
    palette.setBrush(QPalette::Inactive, QPalette::Base, brush2);
    palette.setBrush(QPalette::Inactive, QPalette::HighlightedText, brush1);
    palette.setBrush(QPalette::Disabled, QPalette::Light, brush);
    palette.setBrush(QPalette::Disabled, QPalette::BrightText, brush1);
    QBrush brush3(QColor(235, 233, 237, 255));
    brush3.setStyle(Qt::SolidPattern);
    palette.setBrush(QPalette::Disabled, QPalette::Base, brush3);
    palette.setBrush(QPalette::Disabled, QPalette::HighlightedText, brush1);
    
    return palette;
    
}












